<?php
/**
 * @author phutp@younetco.com
 */
class Core_Util
{ 
	public static function redirect($url) 
	{
		header("Location: $url");
	}
	
	public static function parentRedirect($url) 
	{
		echo "<script language='javascript'>top.location.href='" . $url . "'</script>";
	}
	
	public static function isFacebookRequest()
	{
		$is_fb_request = false;

		if($_SERVER['HTTP_USER_AGENT'] == "facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)")
		{
			$is_fb_request = true;
		}

		return $is_fb_request;
	}
    
    public static function shareUrl($url = '')
	{
		return 'http://' . $_SERVER['HTTP_HOST'] . $url;
	}	
    public static function createScaledThumbnail($source, $thumbnail, $size)
	{
		$storage = Zend_Registry::get('storage');
		if ($storage instanceof YouNet_Storage_S3)
		{
			$source_local = INDEX_PATH . '/../..' . $source;
            $thumbnail_local = INDEX_PATH . '/../..' . $thumbnail;
			$storage->copyToLocal($source_local, $source);
			self::cropScaledThumbnail($source_local, $thumbnail_local, $size);
			$storage->put($thumbnail, file_get_contents($thumbnail_local)); 
		}
		else
		{
			self::cropScaledThumbnail($source, $thumbnail, $size);
		}
	}
	
	public static function cropScaledThumbnail($file_name, $target, $size)
	{
		list($width, $height, $type) = getimagesize($file_name);
		
		$cropHeight = $cropWidth = $size;
		
		if ($width > $height)
		{
			$ratio = $height / $width;
			$cropWidth = $size;
			$cropHeight = round($cropWidth * $ratio);
		}
		else if($width < $height)
		{
			$ratio = $width / $height;
			$cropHeight = $size;
			$cropWidth = round($cropHeight * $ratio);
		}
		else
		{
			$cropWidth = $cropHeight = $size;
		}
        
         $thumb = imagecreatetruecolor($cropWidth, $cropHeight);
         $source;
         switch ($type) {
            case IMAGETYPE_PNG:
                $source = imagecreatefrompng($file_name);
                break;
            case IMAGETYPE_JPEG:
                $source = imagecreatefromjpeg($file_name);
                break;
            case IMAGETYPE_GIF:
                $source = imagecreatefromgif($file_name);
                break;
        }

        imagealphablending($thumb, false);
        imagesavealpha($thumb, true);
        imagecopyresampled($thumb, $source, 0, 0, 0, 0, $cropWidth, $cropHeight, $width, $height);

        switch ($type) {
            case IMAGETYPE_PNG:
                imagepng($thumb, $target);
                break;
            case IMAGETYPE_JPEG:
                imagejpeg($thumb, $target);
                break;
            case IMAGETYPE_GIF:
                imagegif($thumb, $target);
                break;
        }
        return $target;
	}
}